package handler

import (
	"errors"
	"go_20210605/businessError"
	"go_20210605/service"
	"log"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type userHandler struct {
}

var UserHandler = userHandler{}

func (u *userHandler) FindById(c *gin.Context) {
	log.Println("hello")
	idstr := c.Param("id")
	id, err := strconv.Atoi(idstr)
	if err != nil {
		log.Printf("covert id:%s to int err:%v", idstr, err)
		c.JSON(http.StatusBadRequest, gin.H{
			"message": "params err",
		})
		return
	}
	user, err := service.UserService.FindById(id)
	if err != nil {
		//logrus.Errorf("err stack:%+v", errors.Cause(err))
		//logrus.Errorf("err stack:%+v", err)
		//log.Printf("err stack:%v", err)
		log.Printf("err stack:%+v", err)

		//if errors.Cause(err) == sql.ErrNoRows {
		//	c.JSON(http.StatusBadRequest, gin.H{
		//		"message": "not found",
		//	})
		//	return
		//}

		//if errors.Is(err, sql.ErrNoRows) {
		//	c.JSON(http.StatusBadRequest, gin.H{
		//		"message": "not found",
		//	})
		//	return
		//}
		if errors.Is(err, businessError.NOT_FOUND_ERROR) {
			c.JSON(http.StatusBadRequest, gin.H{
				"message": "not found",
			})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{
				"message": "system err",
			})
		}

		return
	}
	c.JSON(http.StatusOK, gin.H{
		"message": "success",
		"data":    user,
	})
}
